<template>
  <div class="action-buttons-container">
    <a-button type="primary" @click="handleQuery">刷新</a-button>
    <a-button class="split-button" type="primary" @click="handleAdd">新增</a-button>
    <a-button class="split-button" type="primary" :disabled="!singleSelect" @click="handleEdit(null)">修改
    </a-button>
    <a-popconfirm
        title="确定删除这条记录?"
        ok-text="确定"
        cancel-text="取消"
        @confirm="handleDelete(null)"
        :disabled="!singleSelect"
    >
      <a-button class="split-button" type="danger" :disabled="!singleSelect">删除</a-button>
    </a-popconfirm>
  </div>
  <a-table :data-source="sysDeptList" :columns="columns" rowKey="id"
           :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
           :pagination="false"
  ></a-table>
  <a-modal v-model:visible="showAddModel" title="新增或修改部门" @ok="handleSave">
    <a-form ref="addFormRef" :model="addForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }" autocomplete="off">
      <a-form-item style="display: none;"
                   label="id"
                   name="id">
        <a-input v-model:value="addForm.id"/>
      </a-form-item>
      <a-form-item
          label="部门名称"
          name="deptName"
          :rules="[{ required: true, message: '请输入部门名称' }]"
      >
        <a-input v-model:value="addForm.deptName"/>
      </a-form-item>
      <a-form-item
          label="序号"
          name="sortNum"
          :rules="[{ required: true, message: '请输入序号' }]"
      >
        <a-input v-model:value="addForm.sortNum"/>
      </a-form-item>
      <a-form-item
          label="上级部门"
          name="parentCode"
          :rules="[{ required: true, message: '请选择上级部门' }]"
      >
        <a-tree-select
            v-model:value="addForm.parentCode"
            :fieldNames="{children:'children', label:'deptName', value: 'deptCode' }"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder=""
            allow-clear
            tree-default-expand-all
            :tree-data="deptSelectTreeData"
        >
        </a-tree-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>

import {onMounted, reactive, ref} from "vue";
import request from '@/util/request.js'
import {message} from "ant-design-vue";
import {showLoading,hideLoading, validValue} from "@/util/util.js";

let showAddModel = ref(false)
let addModelTitle = ref("新增")
let queryForm = reactive({})
let sysDeptList = ref([])
let singleSelect = ref(false)
let selectedRowKeys = ref([])
let selectedRows = ref([])
let addForm = ref({})
let pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
})
const queryFormRef = ref(null);
let addFormRef = ref(null);
const columns = [
  {
    title: '部门名称',
    dataIndex: 'deptName',
    key: 'deptName',
  }, {
    title: '序号',
    dataIndex: 'sortNum',
    key: 'sortNum',
  },
]
onMounted(() => {
  handleQuery()
})
const handleQuery = () => {
  let queryParam = {...queryForm};
  queryParam["currentPage"] = pagination.value.current
  queryParam["pageSize"] = pagination.value.pageSize
  query(queryParam)
}

function handleReset() {
  queryFormRef.value.resetFields();
  handleQuery()
}

const query = (param) => {
  showLoading()
  //请求后端
  request({
    method: 'post',
    url: '/api/system/dept/loadDeptTree',
    data: param
  }).then((response) => {
    hideLoading()
    sysDeptList.value = response.data;
  });
}
const handlePageChange = (current) => {
  pagination.value.current = current
  handleQuery()
}

function handleSave() {
  addFormRef.value.validate().then((res) => {
    showLoading()
    request({
      method: 'post',
      url: '/api/system/dept/addOrUpdate',
      data: res
    }).then((res) => {
      hideLoading()
      if (res.code === 200) {
        showAddModel.value = false;
        message.success("保存成功")
        handleQuery();
      } else {
        message.error("操作失败" + res.errMsg)
      }
    })
  }).catch(() => {
    hideLoading()
  })
}

function handleAdd() {
  //新增
  addModelTitle.value = '新增'
  showAddModel.value = true
  addForm.value = {};
  loadDeptSelectTree();
}

function handleEdit(row) {
  showAddModel.value = true
  addModelTitle.value = '修改'
  //加载数据
  if (!validValue(row)) {
    row = selectedRows.value[0];
  }
  addForm.value = {};
  loadDeptSelectTree();
  showLoading()
  request({
    method: 'get',
    url: '/api/system/dept/selectById',
    params: {id: row.id}
  }).then((res) => {
    hideLoading()
    addForm.value = res.data
  })
}

function handleDelete(row) {
  if (!validValue(row)) {
    row = selectedRows.value[0];
  }
  showLoading()
  request({
    method: 'delete',
    url: '/api/system/dept/deleteById',
    params: {id: row.id}
  }).then((res) => {
    hideLoading()
    if (res.code === 200) {
      message.info('删除成功');
      handleQuery()
    } else {
      message.error("删除失败：" + res.errMsg)
    }
  })
}

function onSelectChange(rowKeys, rows) {
  selectedRowKeys.value = rowKeys
  selectedRows.value = rows
  singleSelect.value = rowKeys && rowKeys.length === 1
}

const deptSelectTreeData = ref([]);

function loadDeptSelectTree() {
  showLoading()
  request({
    method: 'post',
    url: '/api/system/dept/loadDeptTree',
  }).then((response) => {
    hideLoading()
    let root = response.data
    deptSelectTreeData.value = [{deptCode: 'root', deptName: '顶级部门', children: root}]
  })
}

function activated() {
  console.log('activated');
}
</script>
